package com.feiyue.learning.advance.nio;

import java.nio.IntBuffer;

/**
 * Java NIO 的 Buffer 类
 * @author  feiyue
 * @date  2020/4/17
 */
public class BufferDemo {

    public static void main(String[] args) {

        // 创建缓冲区
        IntBuffer buffer = IntBuffer.allocate(10);

        // put 的数据超出 buffer 的容量会报错
        for (int i = 0; i < 9; i++) {
            buffer.put(i);
        }

        // buffer 创建后初始模式为写模式，要读取数据的话需要先切换到读模式
        buffer.flip();
        for (int j = 0; j < buffer.limit(); j++) {
            System.out.print(" " + buffer.get());
        }
        System.out.println("\n读取 position: " + buffer.position());

        // 倒带, 重新开始读取
        buffer.rewind();
        for (int j = 0; j < buffer.limit(); j++) {
            System.out.print(" " + buffer.get());
        }

        // mark 将当前 position 的值保存到 mark 中
        System.out.println("\n buffer position: " + buffer.position());
        buffer.mark();

        // 将 mark 的值恢复到 position 中
        buffer.reset();
        System.out.println("buffer position: " + buffer.position());

        buffer.clear();
        System.out.println("buffer position: " + buffer.position() + ", buffer limit: " + buffer.limit());
    }
}
